<template>
  <Drawer :title="title">
    <Tabs v-model:activeKey="activeKey">
      <TabPane key="1" tab="角色信息">
        <BaseForm />
      </TabPane>
      <template v-if="data.roleCode">
        <TabPane key="2" tab="分配权限">
          <RoleAuth ref="roleAuthRef" @success="onSucClose" />
        </TabPane>
      </template>
    </Tabs>
  </Drawer>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'EditDrawer',
});
import { computed, ref, watch } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { RoleAdd, RoleUpdate } from '../data/api';
import { drawerFormSchema, handleRoleId } from '../data/options';
import { message, Tabs, TabPane } from 'ant-design-vue';
import { useThrottleFn } from '@vueuse/core';
import RoleAuth from './roleAuth.vue';

const emit = defineEmits(['success']);

const activeKey = ref('1');
const data: any = ref({});
const roleAuthRef = ref();
const title = computed(() => {
  return data.value?.roleCode ? '编辑角色' : '新增角色';
});

watch(activeKey, (n, o) => {
  if (n == '2') {
    setTimeout(() => {
      roleAuthRef?.value.refreshData();
    }, 10);
  }
});

//  提交
const onSubmit = useThrottleFn(async (values: Record<string, any>) => {
  console.log(values);
  const { valid } = await formApi.validate();
  if (!valid) return;
  let query = values.roleId ? RoleUpdate : RoleAdd;
  let res: any = await query({ ...values });
  message.success(res.message);
  onSucClose();
}, 1000);

const [Drawer, drawerApi] = useVbenDrawer({
  class: 'w-2/5',
  onCancel() {
    drawerApi.close();
  },
  onConfirm: () => onConfirm(),
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      activeKey.value = '1';
      data.value = drawerApi.getData();
      console.log(data.value);
      handleRoleId.value = data.value?.roleId;
      formApi.setValues({ ...data.value });
    }
  },
});

// 表单
const [BaseForm, formApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  showDefaultActions: false,
  wrapperClass: 'pl-0 pr-4 pt-4 pb-4',
  schema: drawerFormSchema,
  handleSubmit: onSubmit,
  // 所有表单项
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
});

const onSucClose = () => {
  drawerApi.close();
  emit('success');
};

// 提交按钮
const onConfirm = () => {
  if (activeKey.value == '1') {
    formApi.submitForm();
  } else if (activeKey.value == '2') {
    roleAuthRef?.value.onConfirm();
  }
};
</script>

<style lang="scss" scoped></style>
